﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Silvermoon.Controls;
using Passwords.Utils;
using Silvermoon.Shapes;
using Silvermoon.Windows;
using System.Drawing;
using Silvermoon.UI;
using Silvermoon.Images;
using Passwords.Images;
using Passwords.Styles;
using Silvermoon.Animations;
using Silvermoon;
using Passwords.Models;
using Silvermoon.Windows.Styles;
using Silvermoon.Navigation;
using Silvermoon.Controls.Base;
using Passwords.Controllers;
using Silvermoon.Controls.Forms;
using Passwords.Biz;

namespace Passwords.Pages
{
    public class DetailsPage : Page
    {
        #region fields

        ListViewController<NameValueItem, PasswordItem> controller;
        private ButtonBase addFaveButton;
        private Password password;
        private Toolbar toolbar;
        private ListView listView;
        private Label title;
        private Label titleBackground;
        const int passwordTitleHeight = 80;
        private Point titleTransformation;
        private TranslateTransform titleTranslation;
        private TranslateTransform viewTranslation;
        private float viewTransformation = -1f;

        #endregion
        #region ctors

        public DetailsPage()
            : base()
        {
            InitializePage();
        }

        protected override void Dispose(bool dispose)
        {
            PasswordCommands.EditPassword.Executed -= OnEditPassword;
            if (Context.Current != null)
            {
                Context.Current.PasswordDeleted -= OnPasswordDeleted;
            }

            base.Dispose(dispose);
        }

        #endregion
        #region accessors

        public static PropertyAccessor<DetailsPage, Point> TitleTransformationProperty = PropertyAccessor.Register<DetailsPage, Point>("TitleTransformation",
            c => c.TitleTransformation,
            (c, v) => c.TitleTransformation = v);

        public static PropertyAccessor<DetailsPage, float> ViewTransformationProperty = PropertyAccessor.Register<DetailsPage, float>("ViewTransformation",
            c => c.ViewTransformation,
            (c, v) => c.ViewTransformation = v);

        #endregion
        #region props

        public Password Password
        {
            get { return password; }
            set
            {
                if (password != value)
                {
                    password = value;
                    OnPasswordChanged();
                }
            }
        }

        public Point TitleTransformation
        {
            get { return titleTransformation; }
            set
            {
                if (titleTransformation != value)
                {
                    titleTransformation = value;
                    titleTranslation.X = value.X;
                    titleTranslation.Y = value.Y;
                    Invalidate(InvalidationFlag.Transformation);
                }
            }
        }

        public float ViewTransformation
        {
            get { return viewTransformation; }
            set
            {
                if (viewTransformation != value)
                {
                    viewTransformation = value;
                    viewTranslation.Y = -value * Height;
                    Invalidate(InvalidationFlag.Layout);
                }
            }
        }

        public string PasswordTitle
        {
            get { return title.Text; }
            set { title.Text = value; }
        }

        public ListView ListView { get { return listView; } }


        #endregion
        #region methods
        private void InitializePage()
        {
            KeepAlive = false;
            //BackTransition = PageTransition.HideThenShow;

            Styles = StylePool.Metro;
            SetTransition(350, TransitionMask.Fade | TransitionMask.Zoom, TransitionMask.Fade | TransitionMask.Explode);
            Title = "PASSWORDS < DETAILS";

            titleTranslation = new TranslateTransform();
            viewTranslation = new TranslateTransform { };

            listView = new ListView { StyleName = "PasswordDetails", Margin = new Margin(0, passwordTitleHeight + 16, 0, 0), Transformation = viewTranslation };


            title = new Label
            {
                Margin = new Margin(10, 0, 0, null),
                Height = passwordTitleHeight,
                Font = FontCache.BigRegularFont,
                FontScale = 1.3f,
                Transformation = titleTranslation
            };
            titleBackground = new Label
            {
                Margin = new Margin(0, 0, 0, null),
                Height = passwordTitleHeight,
                //Background = GetTitleBackground(),
                Visible = true
            };
            //listBox.Items.Add(detailsGroup);
            Controls.Add(titleBackground, listView, title);

            toolbar = new Toolbar();
            toolbar.Buttons.Add(new ToolbarButton { Content = SysImages.Back, Command = Page.BackCommand });
            toolbar.Buttons.Add(new ToolbarButton { Content = ImagePool.AddFave });
            //toolbar.Buttons.Add(new ToolbarButton { Content = SysImages.RecycleBin, Command = PasswordCommands.DeletePassword });
            toolbar.Buttons.Add(new ToolbarButton { Content = SysImages.Edit, Command = PasswordCommands.EditPassword });

            addFaveButton = toolbar.Buttons[1];
            addFaveButton.Tap += new EventHandler<TapEventArgs>(OnAddFave);

            Style = StylePool.Window;
            Toolbar = toolbar;
            Context.Current.PasswordDeleted += new EventHandler<PasswordEventArgs>(OnPasswordDeleted);
            PasswordCommands.EditPassword.Executed += OnEditPassword;

        }

        void OnAddFave(object sender, TapEventArgs e)
        {
            password.IsFavorite = true;
            try
            {
                password.Save();
                addFaveButton.Enabled = false;
            }
            catch (Exception)
            {
                password.IsFavorite = false;
                MessageDialog.Show("Error", "Could not add password " + password.Name + " to favorites.");
            }
        }

        void OnEditPassword(object sender, CommandEventArgs e)
        {
            Password pw = password;
            EditDetailsPage editPage = new EditDetailsPage { Password = pw };
            this.NavigateTo(editPage);
        }

        protected override void OnShowing()
        {
            controller.BindItems();
            //listView.InvalidateItems();
            base.OnShowing();
        }

        protected override void OnCommand(CommandEventArgs args)
        {
            var command = args.Command as Command;
            if (command == PasswordCommands.DeletePassword)
            {
                args.Object = Password;
            }
            base.OnCommand(args);
        }

        void OnPasswordDeleted(object sender, PasswordEventArgs e)
        {
            Context.Current.PasswordDeleted -= OnPasswordDeleted;
            GoBack();
        }

        protected override void OnHome(HandledEventArgs e)
        {
            KeepAlive = false;
            //SetTransition(350, TransitionMask.RotateLeftIn, 350, TransitionMask.RotateLeftOut);
            base.OnHome(e);
        }

        protected virtual void OnPasswordChanged()
        {
            AppController.CurrentPassword = password;
            PasswordTitle = password.Name;
            controller = DetailControllerHelper.InitializeView(ListView, password, true);
            addFaveButton.Enabled = !password.IsFavorite;
        }

        private class Bag
        {
            public int YOffset;
            public Password Password;
        }

        public override object OnSaveViewState()
        {
            return new Bag { YOffset = listView.YOffset, Password = password };
        }

        public override void OnLoadViewState(object viewState)
        {
            Bag bag = viewState as Bag;
            if (bag != null)
            {
                Password = bag.Password;
                listView.YOffset = bag.YOffset;
            }
        }

        #endregion
    }
}
